//
//  VRMainViewController.m
//  VRContact
//
//  Created by Veer on 2017/3/30.
//  Copyright © 2017年 veer. All rights reserved.
//

#import "VRMainViewController.h"
#import "VRAddressBookViewController.h"
#import <AddressBook/AddressBook.h>

#import "VRAddressBookTool.h"
#import "UIImage+VR.h"
#import "VRAddressBookModel.h"


@interface VRMainViewController () <UIAlertViewDelegate, UITextFieldDelegate, UIAlertViewDelegate>{

    double angle;
}

/** 联系人总数 */
@property (nonatomic, weak) UILabel *contactsCountLbl;
/** 进度view */
@property (nonatomic, weak) UIView *progressView;
/** 同步按钮 */
@property (nonatomic, weak) UIButton *syncBtn;
/** 同步按钮 */
@property (nonatomic, weak) UIView *loginMaskView;
/** 钮 */
@property (nonatomic, weak) UITextField *usernameTf;


/** 旋转动画 */
@property (nonatomic, strong) CABasicAnimation *rotationAnimation;

/** 是否开始同步 */
@property (nonatomic, assign) BOOL isStartSync;

@end

@implementation VRMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor redColor];
    
    [self setupSubView];
//    [self setupTestBtn];
//    [self setupLoginView];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    // 开启返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    
}


- (void)setupTestBtn
{
    
    UIButton *startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    startBtn.tag = 100;
    [startBtn setTitle:@"login" forState:UIControlStateNormal];
    [startBtn addTarget:self action:@selector(onStartAndStopBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startBtn];
    [startBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-100);
        make.top.mas_equalTo(50);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(40);
    }];
    
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];\
    sendBtn.tag = 200;
    [sendBtn setTitle:@"send" forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(onStartAndStopBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn];
    [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-50);
        make.top.mas_equalTo(50);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(40);
    }];
}


- (void)setupSubView
{
    // 背景图
    UIImageView *bgImgView = [[UIImageView alloc] init];
    bgImgView.contentMode = UIViewContentModeScaleAspectFill;
    bgImgView.image = [UIImage imageNamed:@"mian_bg"];
    bgImgView.clipsToBounds = YES;
    [self.view addSubview:bgImgView];
    [bgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
//        make.height.mas_equalTo(520 * VRScreenScale);
        make.bottom.mas_equalTo(self.view);
    }];
    
    
    UILabel *contactsCountLbl = [[UILabel alloc] init];
//    contactsCountLbl.text = [NSString stringWithFormat:@"共有%ld位联系人", contactsCount];
    contactsCountLbl.text = @"共有0位联系人";
    contactsCountLbl.textAlignment = NSTextAlignmentCenter;
    contactsCountLbl.font = [UIFont systemFontOfSize:18];
    contactsCountLbl.textColor = [UIColor whiteColor];
    [self.view addSubview:contactsCountLbl];
    self.contactsCountLbl = contactsCountLbl;
    [contactsCountLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(40);
    }];
    
    
    // 退出按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    //    [button setImage:[UIImage imageNamed:@"back_button"] forState:UIControlStateNormal];
    [button setTitle:@"退出" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:18];;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_equalTo(contactsCountLbl);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(70);
    }];
    
    // 进度
    UIView *barView = [[UIView alloc] init];
    barView.backgroundColor = VRColorAlpha(55, 101, 171, 0.7);
    [self.view addSubview:barView];
    [barView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(bgImgView.mas_bottom);
        make.height.mas_equalTo(130 * VRScreenScale);
    }];
    
    
    UIView *progressView = [[UIView alloc] init];
    progressView.backgroundColor = VRColorAlpha(144, 192, 50, 0.4);
    [self.view addSubview:progressView];
    self.progressView = progressView;
    [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view);
        make.bottom.mas_equalTo(bgImgView.mas_bottom);
        make.height.mas_equalTo(130 * VRScreenScale);
        make.width.mas_equalTo(0);
    }];
    
    // 提示文字
    UILabel *tipLbl = [[UILabel alloc] init];
    tipLbl.text = @"点击右边按钮\n进行上传";
    tipLbl.numberOfLines = 0;
    tipLbl.textAlignment = NSTextAlignmentCenter;
    tipLbl.font = [UIFont systemFontOfSize:20];
    tipLbl.textColor = [UIColor whiteColor];
    [self.view addSubview:tipLbl];
    [tipLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_equalTo(progressView);
    }];
    
    // 按钮
    UIButton *syncBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [syncBtn setBackgroundImage:[UIImage imageNamed:@"bigbtn_bg_def"] forState:UIControlStateNormal];
    [syncBtn setBackgroundImage:[UIImage imageNamed:@"bigbtn_bg_def"] forState:UIControlStateDisabled];
    [syncBtn setBackgroundImage:[UIImage imageNamed:@"bigbtn_btn_pre"] forState:UIControlStateHighlighted];
    [syncBtn setImage:[UIImage imageNamed:@"bigbtn_icon"] forState:UIControlStateNormal];
    [syncBtn setImage:[UIImage imageNamed:@"bigbtn_icon"] forState:UIControlStateDisabled];
    [syncBtn setImage:[UIImage imageNamed:@"bigbtn_icon"] forState:UIControlStateHighlighted];
    
    [syncBtn addTarget:self action:@selector(onSyncBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:syncBtn];
    self.syncBtn = syncBtn;
    [syncBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-40);
        make.centerY.mas_equalTo(progressView.mas_top);
        make.width.height.mas_equalTo(125 * VRScreenScale);
    }];
    
    // 判断是否授权
    ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus();
    if (authorizationStatus == kABAuthorizationStatusNotDetermined) {
        
        // 请求授权
        ABAddressBookRef addressBookRef = ABAddressBookCreate();
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            if (granted) { // 授权成功
                
                NSLog(@"授权成功！");
                dispatch_async(dispatch_get_main_queue(), ^{
                    contactsCountLbl.text = [NSString stringWithFormat:@"共有%ld位联系人", [VRAddressBookTool getContactsCount]];
                });
            } else {  // 授权失败
                contactsCountLbl.text = @"未授权";
            }
        });
        
    }else if (authorizationStatus == kABAuthorizationStatusDenied){
        
        contactsCountLbl.text = @"未授权";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请到设置->隐私->通讯录服务->【雅同】中开启,已便获取通讯录信息!" delegate:self cancelButtonTitle:@"残忍拒绝" otherButtonTitles:@"确认", nil];
        [alertView show];
    }else{
    
        contactsCountLbl.text = [NSString stringWithFormat:@"共有%ld位联系人", [VRAddressBookTool getContactsCount]];
    }
}


- (void)dismissLoginView
{
    
    
}


- (void)setupLoginView
{
    
//    UIAlertView *loginView = [[UIAlertView alloc] initWithTitle:@"login" message:nil delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"login", nil];
//    loginView.alertViewStyle = UIAlertViewStylePlainTextInput;
//    UITextField *tf = [loginView textFieldAtIndex:0];
//    tf.placeholder = @"username";
//    [loginView show];
    UIView *maskView = [[UIView alloc] init];
    maskView.backgroundColor = VRColorAlpha(0, 0, 0, 0.4);
    [self.view addSubview:maskView];
    self.loginMaskView = maskView;
    [maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    UIView *loginView = [[UIView alloc] init];
    loginView.backgroundColor = [UIColor whiteColor];
    loginView.layer.masksToBounds = YES;
    loginView.layer.cornerRadius = 5;
    [maskView addSubview:loginView];
    [loginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(maskView).offset(-100);
        make.height.mas_equalTo(150);
    }];
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"登陆";
    titleLbl.textAlignment = NSTextAlignmentCenter;
    titleLbl.textColor = VRColor(100, 100, 100);
    titleLbl.font = VRFont(16);
    [loginView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    
    UITextField *usernameTf = [[UITextField alloc] init];
    usernameTf.placeholder = @"请输入用户名";
    usernameTf.returnKeyType = UIReturnKeyGo;
    usernameTf.font = VRFont(15);
    usernameTf.layer.borderColor = VRColor(0xbb, 0xbb, 0xbb).CGColor;
    usernameTf.layer.borderWidth = 0.5;
    usernameTf.layer.masksToBounds = YES;
    usernameTf.layer.cornerRadius = 5;
    usernameTf.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    usernameTf.leftViewMode = UITextFieldViewModeAlways;
    usernameTf.delegate = self;
    [loginView addSubview:usernameTf];
    self.usernameTf = usernameTf;
    [usernameTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleLbl.mas_bottom).offset(15);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(35);
    }];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setTitle:@"登陆" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = VRFont(16);
    [loginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageWithColor:VRColor(240, 240, 240)] forState:UIControlStateHighlighted];
    [loginBtn addTarget:self action:@selector(onLoginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [loginView addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = VRColor(0xbb, 0xbb, 0xbb);
    [loginView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(loginBtn.mas_top);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];
    
    [usernameTf becomeFirstResponder];
    
    NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
    NSString *userName = [userdef valueForKey:VRUsernameKey];
    if (userName) {
        
        usernameTf.text = userName;
    }
}


//暂停动画
- (void)pauseAnimation {
    
    //（0-5）
    //开始时间：0
    //    myView.layer.beginTime
    //1.取出当前时间，转成动画暂停的时间
    CFTimeInterval pauseTime = [self.syncBtn.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    
    //2.设置动画的时间偏移量，指定时间偏移量的目的是让动画定格在该时间点的位置
    self.syncBtn.imageView.layer.timeOffset = pauseTime;
    
    //3.将动画的运行速度设置为0， 默认的运行速度是1.0
    self.syncBtn.imageView.layer.speed = 0;
    
}

//恢复动画
- (void)resumeAnimation {
    
    //1.将动画的时间偏移量作为暂停的时间点
    CFTimeInterval pauseTime = self.syncBtn.imageView.layer.timeOffset;
    
    //2.计算出开始时间
    CFTimeInterval begin = CACurrentMediaTime() - pauseTime;
    
    [self.syncBtn.imageView.layer setTimeOffset:0];
    [self.syncBtn.imageView.layer setBeginTime:begin];
    
    self.syncBtn.imageView.layer.speed = 1;
}





- (void)startAnimation
{
    
    [self.syncBtn.imageView.layer addAnimation:self.rotationAnimation forKey:@"rotationAnimation"];
}


- (void)stopAnimation
{
    
    [self.syncBtn.imageView.layer removeAllAnimations];
}


//手动设置 cookies
-(void)setCurcookies{
    
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in storage.cookies) {
        [storage deleteCookie:cookie];
    }
    NSLog(@"%@",storage.cookies);
    NSUserDefaults *usedef = [NSUserDefaults standardUserDefaults];
    NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:[usedef objectForKey:@"doctorcookiesKey"]];
    
    for (NSHTTPCookie *cookie in cookies) {
        [storage setCookie:cookie];
    }
    NSLog(@"%@",storage.cookies);
}


- (void)clearCookies
{
    
    // 存账号密码
    NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
    [userdef removeObjectForKey:VRLoginCookieKey];
    [userdef synchronize];
    
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in storage.cookies) {
        [storage deleteCookie:cookie];
    }
}


#pragma mark - action
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onSyncBtnClick:(UIButton *)sender
{
    
    // 判断是否授权
    ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus();
    if (authorizationStatus == kABAuthorizationStatusNotDetermined) {
        // 请求授权
        
    }else if (authorizationStatus == kABAuthorizationStatusDenied){
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请到设置->隐私->通讯录服务->【雅同】中开启,已便获取通讯录信息!" delegate:self cancelButtonTitle:@"残忍拒绝" otherButtonTitles:@"确认", nil];
        [alertView show];
    }else{
        
        sender.enabled = YES;
        [self startAnimation];
        [self uploadContacts];
    }
}


- (void)onStartAndStopBtnClick:(UIButton *)sender
{
    
    if (sender.tag == 100) {
        
        [self loginWith:@"xxb-5000"];
    }else if (sender.tag == 200){
        
        [self uploadContacts];
    }
    
}


- (void)onLoginBtnClick:(UIButton *)sender
{
    
    [self.view endEditing:YES];
    
    NSString *userName = self.usernameTf.text;
    if (userName.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入用户名"];
        [self.usernameTf becomeFirstResponder];
        return;
    }
    
    [self loginWith:userName];
//    [UIView animateWithDuration:0.25 animations:^{
//        
//        self.loginMaskView.alpha = 0;
//    } completion:^(BOOL finished) {
//        
//        [self.loginMaskView removeFromSuperview];
//        self.loginMaskView = nil;
//    }];
}


// 字典转json字符串方法

-(NSString *)convertToJsonData:(id)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0, jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

#pragma mark - net
/** login */
- (void)loginWith:(NSString *)userName
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"card"] = userName;
    
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
//    sessionMgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    
    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];
    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;
    
    sessionMgr.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    
    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionMgr.requestSerializer.timeoutInterval = 10.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [sessionMgr POST:API_Login parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 返回：struts=0 登录成功   struts=1  账号有误请重新登录
        VRLog(@"responseObject:%@", responseObject);
        NSInteger struts = [responseObject[@"struts"] integerValue];
        
        if (struts == 0) {
            
            [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
            self.username = self.usernameTf.text;
            
            [UIView animateWithDuration:0.25 animations:^{
                
                self.loginMaskView.alpha = 0;
            } completion:^(BOOL finished) {
                
                [self.loginMaskView removeFromSuperview];
                self.loginMaskView = nil;
            }];
            
            // 存账号密码
            NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
            [userdef setValue:userName forKey:VRUsernameKey];
            [userdef synchronize];
            
            NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
            for (int i = 0;  i < cookieJar.cookies.count; i ++) {
                
                NSHTTPCookie *cookie = [cookieJar cookies][i];
                if (i == cookieJar.cookies.count - 1) {
                    
                    [userdef setValue:cookie.value forKey:VRLoginCookieKey];
                    
                    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:@[cookie]];
                    [userdef setObject:cookiesData forKey:@"doctorcookiesKey"];
                    
                    [userdef synchronize];
                }
            }
            
        }else if (struts == 1){
            
            [SVProgressHUD showErrorWithStatus:@"账号有误请重新登录"];
            [self.usernameTf becomeFirstResponder];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        VRLog(@"error:%@", error);
        
        if (error.code == -1009) {  // 网络连接错误
            
            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
        }
    }];
    
}


/** 上传联系人 */
- (void)uploadContacts
{
    
    NSMutableArray *contactDicts = [VRAddressBookTool getContactsWithBlock:nil];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    NSDictionary *dict = @{@"datas":@"123"};
    NSArray *array = @[@{@"name" : @"panxx1", @"phone" : @""},
                       @{@"name" : @"", @"phone" : @"18257149139"},
                       @{@"name" : @"panxx3", @"phone" : @"18257149139"},
                       @{@"name" : @"panxx4", @"phone" : @"18257149139"},
                       @{@"name" : @"panxx5", @"phone" : @"18257149139"}];
//    param[@"datas"] = @"[{\"name\":\"panxx\", \"phone\":\"18257149139\"}]";
    NSString *jsonStr = [self convertToJsonData:contactDicts];
    param[@"card"] = self.username;
    param[@"datas"] = jsonStr;
    
    VRLog(@"param:%@", param);
    
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
//    [sessionMgr setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
//        
//        return nil;
//        
//    }];
    
    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];
    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;
    
    sessionMgr.requestSerializer=[AFHTTPRequestSerializer serializer];
    
    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionMgr.requestSerializer.timeoutInterval = 10.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [sessionMgr POST:API_Backup parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        VRLog(@"responseObject:%@", responseObject);
        
        NSInteger struts = [responseObject[@"struts"] integerValue];
        if (struts == 1){
            
            [SVProgressHUD showErrorWithStatus:@"未登录"];
            [self clearCookies];
            [self setupLoginView];
        }else if (struts == 2){
            
            [SVProgressHUD showErrorWithStatus:@"上传数据为空"];
        }else if (struts == 3){
            
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
        }
        
        [self stopAnimation];
        self.syncBtn.enabled = YES;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        VRLog(@"error:%@", error);
        if (error.code == -1009) {  // 网络连接错误
            
            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"请求错误"];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{

            self.progressView.width = 0;
            [self stopAnimation];
            self.syncBtn.enabled = YES;
        });
        
    }];
    
    [sessionMgr.operationQueue cancelAllOperations];
}


#pragma mark - setter and getter
- (CABasicAnimation *)rotationAnimation

{
    
    if (_rotationAnimation == nil) {
        
        //动画
        _rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        
        _rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
        
        _rotationAnimation.duration = 0.8;
        
        _rotationAnimation.cumulative = YES;
        
        _rotationAnimation.repeatCount = HUGE_VALF;
    }
    
    return _rotationAnimation;
}



- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

#pragma mark - delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 1) {
        
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}


#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self onLoginBtnClick:nil];
    return YES;
}


@end
